//
//  PharmacyViewController.m
//  110
//
//  Created by 沈鑫 on 16/4/11.
//  Copyright © 2016年 乔砥. All rights reserved.
//

#import "PharmacyViewController.h"
#import "PriceTableViewCell.h"
#import "CommentTableViewCell.h"
#import "ExpositionTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "RequestManager.h"
#import "PriceModel.h"
#import "CommentModel.h"
#import "ExpositionModel.h"
#import "BuyViewController.h"
@interface PharmacyViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIView *headeView;
@property (nonatomic, strong)UIImageView *headeImageView;
@property (nonatomic, strong)UILabel *titleLable;
@property (nonatomic, strong)UILabel *deatileLabel;
@property (nonatomic, strong)UILabel *textLabel;
@property (nonatomic, strong)UIImageView *starImageView;
@property (nonatomic, strong)UILabel *dateLabel;
@property (nonatomic, strong)UIButton *priceButton;
@property (nonatomic, strong)UIButton *commentButton;
@property (nonatomic, strong)UIButton *expositionButton;
@property (nonatomic, strong)UIView *lView;
@property (nonatomic, strong)UIView *lView1;
@property (nonatomic, strong)UIScrollView *bigScrollView;
@property (nonatomic, strong)NSMutableArray *pricrArray;
@property (nonatomic, strong)NSMutableArray *commentArray;
@property (nonatomic, strong)ExpositionModel *expositionModel;
// 第二个界面的属性
@property (nonatomic, strong)UITableView *tableView1;
// 第三个界面的属性
@property (nonatomic, strong)UITableView *tableView2;

@end

@implementation PharmacyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"药品详情";
    // navigation两边button 的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    // navigation字体的颜色 大写 型号
    [self.navigationController.navigationBar setTitleTextAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"Arial-BoldItalicMT" size:19],
                                                                       
                                                                       
                                                                       NSForegroundColorAttributeName:[UIColor whiteColor]}];
   
  
        _bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT)];
        _bigScrollView.delegate = self;
        _bigScrollView.pagingEnabled = YES;
        _bigScrollView.bounces = NO;
        _bigScrollView.contentOffset = CGPointMake(0, 0);
        _bigScrollView.contentSize = CGSizeMake(KWIDTH * 3, KHEIGHT - 64);
        [self.view addSubview:_bigScrollView];
        
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, KHEIGHT / 4, KWIDTH, KHEIGHT - 120 - KHEIGHT / 4)];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self.bigScrollView addSubview:_tableView];
        
        // 第二个界面
        self.tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(KWIDTH, KHEIGHT / 4, KWIDTH, KHEIGHT - 120 - KHEIGHT / 4)];
        self.tableView1.delegate = self;
        self.tableView1.dataSource = self;
        [self.bigScrollView addSubview:_tableView1];
        
        // 第三个界面
        self.tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(KWIDTH * 2, KHEIGHT / 4, KWIDTH, KHEIGHT - 120 - KHEIGHT / 4)];
        self.tableView2.delegate = self;
        self.tableView2.dataSource = self;
        [self.bigScrollView addSubview:_tableView2];
        
        // 注册
        [self.tableView registerClass:[PriceTableViewCell class] forCellReuseIdentifier:@"cell1"];
        [self.tableView1 registerClass:[CommentTableViewCell class] forCellReuseIdentifier:@"cell2"];
        [self.tableView2 registerClass:[ExpositionTableViewCell class] forCellReuseIdentifier:@"cell3"];
        
        
        self.headeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT / 4)];
        [self.view addSubview:_headeView];
        
        _headeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 30, 80, 80)];
    
        [self.headeView addSubview:_headeImageView];
        
        _titleLable = [[UILabel alloc]initWithFrame:CGRectMake(100, 5, KWIDTH - 120, 15)];
        _titleLable.textColor = [UIColor blueColor];
    
        [self.headeView addSubview:_titleLable];
        
        _deatileLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 20, KWIDTH - 120, 20)];
        _deatileLabel.textColor = [UIColor blackColor];
        _deatileLabel.font = [UIFont systemFontOfSize:13];
        [self.headeView addSubview:_deatileLabel];
        
        _textLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 40, KWIDTH - 140, 50)];
        _textLabel.numberOfLines = 0;
        _textLabel.font = [UIFont systemFontOfSize:11];
        [self.headeView addSubview:_textLabel];
        
        _starImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 85, 100, 30)];
        
        [self.headeView addSubview:_starImageView];
        
        _dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH - 55, 85, 50, 30)];
        _dateLabel.textColor = [UIColor redColor];
        [self.headeView addSubview:_dateLabel];
    
        _priceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_priceButton setTitle:@"价格" forState:UIControlStateNormal];
        _priceButton.frame = CGRectMake(0, KHEIGHT / 4 - 31, KWIDTH / 3, 30);
        [_priceButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_priceButton addTarget:self action:@selector(changeFrameAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.headeView addSubview:_priceButton];
        
        _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_commentButton setTitle:@"用药点评" forState:UIControlStateNormal];
        _commentButton.frame = CGRectMake(KWIDTH / 3, KHEIGHT / 4 - 31, KWIDTH / 3, 30);
        [_commentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_commentButton addTarget:self action:@selector(changeFrameAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.headeView addSubview:_commentButton];
        
        _expositionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _expositionButton.frame = CGRectMake(KWIDTH / 3 * 2, KHEIGHT / 4 - 31, KWIDTH / 3, 30);
        [_expositionButton setTitle:@"说明书" forState:UIControlStateNormal];
        [_expositionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_expositionButton addTarget:self action:@selector(changeFrameAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.headeView addSubview:_expositionButton];
        
        _lView1 = [[UIView alloc]initWithFrame:CGRectMake(0, KHEIGHT / 4 - 1, KWIDTH, 1)];
        _lView1.backgroundColor = [UIColor lightGrayColor];
        [self.headeView addSubview:_lView1];
        
        _lView = [[UIView alloc]initWithFrame:CGRectMake(0, KHEIGHT / 4 - 1, KWIDTH / 3, 1)];
        _lView.backgroundColor = [UIColor blueColor];
        [self.headeView addSubview:_lView];
    
    

        
        [self requestPrice];
        [self requestComment];
        [self resquestExposition];
}

#pragma mark --- 点击button切换页面方法 ---
- (void)changeFrameAction:(UIButton *)button
{
    if (button == _priceButton)
    {
        _bigScrollView.contentOffset = CGPointMake(0, 0);
    }
    else if (button == _commentButton)
    {
        _bigScrollView.contentOffset = CGPointMake(KWIDTH, 0);
    }
    else
    {
        _bigScrollView.contentOffset = CGPointMake(KWIDTH * 2, 0);
    }
    [UIView animateWithDuration:0.5 animations:^{
        _lView.frame = CGRectMake(_bigScrollView.contentOffset.x / 3, KHEIGHT / 4 - 1, KWIDTH / 3, 1);
    }];
}

#pragma mark --- 滑动结束方法 ---
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView != _bigScrollView)
    {
        return;
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
            _lView.frame = CGRectMake(_bigScrollView.contentOffset.x / 3, KHEIGHT / 4 - 1, KWIDTH / 3, 1);
        }];
    }
    
    
}



// 药品价格网络请求
- (void)requestPrice
{
    NSString *url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugPrice?app_key=app&drugId=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5&ver=2",_homeModel._id];
    
    // 默认是首页跳过来的
    [_headeImageView sd_setImageWithURL:[NSURL URLWithString:_homeModel.TitleImg] placeholderImage:[UIImage imageNamed:@"zanwutupian"]];
    
    _titleLable.text = _homeModel.NameCN;
    if ([_homeModel.NewOTC isEqualToString:@"1"] || [_homeModel.NewOTC isEqualToString:@"2"])
    {
        _dateLabel.text = @"OTC";
    }
    else if ([_homeModel.NewOTC isEqualToString:@"3"])
    {
        _deatileLabel.text = @"Rx";
    }
    [self.headeView addSubview:_dateLabel];

    
    if (_towBool == 1)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugPrice?app_key=app&drugId=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5&ver=2",_HomeImageModel._id];
        [_headeImageView sd_setImageWithURL:[NSURL URLWithString:_HomeImageModel.TitleImg] placeholderImage:[UIImage imageNamed:@"zanwutupian"]];
        _titleLable.text = _HomeImageModel.NameCN;
        if ([_HomeImageModel.NewOTC isEqualToString:@"1"] || [_HomeImageModel.NewOTC isEqualToString:@"2"])
        {
            _dateLabel.text = @"OTC";
        }
        else if ([_HomeImageModel.NewOTC isEqualToString:@"3"])
        {
            _deatileLabel.text = @"Rx";
        }
        [self.headeView addSubview:_dateLabel];


    }
    else if (_towBool == 2)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugPrice?app_key=app&drugId=%ld&sign=9DFAAD5404FCB6168EA6840DCDFF39E5&ver=2",_classModel._id];
        
        [_headeImageView sd_setImageWithURL:[NSURL URLWithString:_classModel.titleimg] placeholderImage:[UIImage imageNamed:@"zanwutupian"]];
        _titleLable.text = _classModel.namecn;
        
        _dateLabel.text = @"OTC";
        [self.headeView addSubview:_dateLabel];
    }
        [RequestManager requestWithUrl:url requestType:RequestTypeGET parDic:nil finish:^(NSData *data)
    {
        NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       _pricrArray = [PriceModel getData:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"药品价格网络错误");
    }];
}


// 药品点评网络请求
- (void)requestComment
{
    NSString *url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugComments?Limit=30&app_key=app&curPage=1&drugId=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_homeModel._id];
    if (_towBool == 1)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugComments?Limit=30&app_key=app&curPage=1&drugId=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_HomeImageModel._id];
    }
    else if (_towBool == 2)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugComments?Limit=30&app_key=app&curPage=1&drugId=%ld&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_classModel._id];
    }
    [RequestManager requestWithUrl:url requestType:RequestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        _commentArray = [CommentModel getData:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView1 reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"药品点评网络错误");
    }];
}

// 药品说明书网络请求
- (void)resquestExposition
{
    NSString *url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugById?app_key=app&id=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_homeModel._id];
    if (_towBool == 1)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugById?app_key=app&id=%@&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_HomeImageModel._id];
    }
    else if (_towBool == 2)
    {
        url = [NSString stringWithFormat:@"http://openapi.db.39.net/app/GetDrugById?app_key=app&id=%ld&sign=9DFAAD5404FCB6168EA6840DCDFF39E5",_classModel._id];
    }
    [RequestManager requestWithUrl:url requestType:RequestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _expositionModel = [ExpositionModel getData:dic];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView2 reloadData];
            // 在主线程赋值图片
            if (_expositionModel.score == 1)
            {
                _starImageView.image = [UIImage imageNamed:@"one"];
            }
            else if (_expositionModel.score == 2)
            {
                _starImageView.image = [UIImage imageNamed:@"two"];
            }
            else if (_expositionModel.score == 3)
            {
                _starImageView.image = [UIImage imageNamed:@"three"];
            }
            else if (_expositionModel.score == 4)
            {
                _starImageView.image = [UIImage imageNamed:@"four"];
            }
            else
            {
                _starImageView.image = [UIImage imageNamed:@"five"];
            }
            _deatileLabel.text = _expositionModel.refdrugcompanyname;
            _textLabel.text = _expositionModel.gongneng;
            
        });
    } error:^(NSError *error) {
        NSLog(@"药品说明书网络请求错误");
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        PriceTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
        // 取消渲染
        cell1.selectionStyle = UITableViewCellAccessoryNone;
        PriceModel *model = _pricrArray[indexPath.row];
        [cell1 getModel:model];
        return cell1;
    }
    if (tableView == _tableView1)
    {
        CommentTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        
        if (!cell2)
        {
            CommentTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
            [cell2.button addTarget:self action:@selector(zabButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            cell2.button.tag = indexPath.row;
        }
        // 取消渲染
        cell2.selectionStyle = UITableViewCellAccessoryNone;
        CommentModel *model = _commentArray[indexPath.row];
        
        [cell2 cellConfigurenodel:model];
//        cell2.backgroundColor = [UIColor lightGrayColor];
        return cell2;
        
    }
    else
    {
        ExpositionTableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        // 取消渲染
        cell3.selectionStyle = UITableViewCellAccessoryNone;
        [cell3 getModel:_expositionModel];
      
        return cell3;
    }
}

#pragma mark --- 点击赞变颜色 ---
- (void)zabButtonAction:(UIButton *)button
{
    button.backgroundColor = [UIColor yellowColor];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableView)
    {
        return _pricrArray.count;
    }
    else if (tableView == _tableView1)
    {
        return _commentArray.count;
    }
    else
    {
        return 1;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        return 40;
    }
    else if (tableView == _tableView1)
    {
        CommentModel *model = _commentArray[indexPath.row];
        return [CommentTableViewCell cellHeghtForRow:model];
    }
    else
    {
        return 1400;
    }
    
}

#pragma mark --- 跳转购买界面 ---
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        BuyViewController *buy = [[BuyViewController alloc]init];
        PriceModel *model = _pricrArray[indexPath.row];
        buy.saleurl = model.saleurl;
        [self.navigationController pushViewController:buy animated:YES];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
